package com.pmx.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pmx.common.utils.PageUtils;
import com.pmx.common.utils.Query;
import com.pmx.mall.product.dao.BrandDao;
import com.pmx.mall.product.dao.CategoryBrandRelationDao;
import com.pmx.mall.product.entity.BrandEntity;
import com.pmx.mall.product.service.BrandService;
import com.pmx.mall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<>();
        // 1.获取key
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            // 2.添加对应的查询条件
            wrapper.eq(BrandEntity::getBrandId, key).or().like(BrandEntity::getName, key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 更新品牌信息
     *
     * @param brand
     */
    @Transactional
    @Override
    public void updateDetail(BrandEntity brand) {
        // 1.更新品牌原始数据（品牌表）
        this.updateById(brand);
        // 2.更新冗余数据
        if (!StringUtils.isEmpty(brand.getName())) {
            // 更新级联关系中的品牌name，品牌-分类关系表
            categoryBrandRelationService.updateBrandName(brand.getBrandId(), brand.getName());
            // TODO 同步更新其他的品牌名称的冗余数据
        }
    }

}